from django.shortcuts import HttpResponse
from .models import UserInfo
from django import forms
import re
import hashlib
import django_redis


class UserInfoForms(forms.ModelForm):
    password = forms.CharField(label='密码', widget=forms.PasswordInput)
    re_password = forms.CharField(label='确认密码', widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    code = forms.CharField(label='短信验证码', widget=forms.TextInput, )

    class Meta:
        model = UserInfo
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = f'请输入{field.label}'

    def clean_mobile_phone(self):
        """
        验证手机号码是否合法
        """
        mobile = self.cleaned_data['mobile_phone']
        REGEX_MOBILE = "^1[358]\d{9}$|^147\d{8}$|^176\d{8}$"
        p = re.compile(REGEX_MOBILE)
        if p.match(mobile):
            return mobile
        else:
            raise forms.ValidationError("手机号码非法", code="mobile_invalid")

    def clean(self):
        # 判断两次输入的密码是否一致
        if self.cleaned_data['password'] == self.cleaned_data['re_password']:
            pwd = self.cleaned_data['password']
            md5 = hashlib.md5()
            md5.update(pwd.encode('utf-8'))
            self.cleaned_data['password'] = md5.hexdigest()

            # 判断短信验证码是否一致
            conn = django_redis.get_redis_connection('default')
            code_redis = conn.get(self.cleaned_data['mobile_phone'])
            if code_redis.decode('utf-8') == self.cleaned_data['code']:
                return self.cleaned_data
            else:
                raise ValueError('验证码不一致')
        else:
            raise ValueError('密码不一致')
